﻿using Batman.Common.Configuration;
using Batman.Common.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace Batman.Common.Extensions
{
    public static class HostingEnvironmentExtension
    {
        /// <summary>
        /// 获取AppSetting.json读取对象
        /// </summary>
        /// <param name="env"></param>
        /// <returns></returns>
        public static IConfigurationRoot GetAppConfigurations(this IHostingEnvironment env)
        {
            return AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName);
        }

        /// <summary>
        /// 获取授权服务器信息
        /// </summary>
        /// <param name="env"></param>
        /// <returns></returns>
        public static AuthorizationHost GetAuthorizationHost(this IHostingEnvironment env)
        {
            // 授权服务器地址配置，固定在根节点
            var section = env.GetAppConfigurations().GetSection("Authorization");
            int.TryParse(section["Port"], out var port);

            var authorizationHost = new AuthorizationHost
            {
                Host = section["Host"],
                Schema = section["Schema"],
                Port = port
            };

            return authorizationHost;
        }

        /// <summary>
        /// 获取配置授权信息
        /// </summary>
        /// <param name="env"></param>
        /// <returns></returns>
        public static AuthenticationInfo GetAuthenticationInfo(this IHostingEnvironment env)
        {
            // 授权服务器地址配置，固定在根节点
            var section = env.GetAppConfigurations().GetSection("Authentication");
            int.TryParse(section["Port"], out var port);

            var authenticationInfo = new AuthenticationInfo
            {
                CallbackPath = section["CallbackPath"],
                DisplayName = section["DisplayName"],
                ModuleName = section["ModuleName"],
                ClientId = section["ClientId"],
                Authority = section["Authority"],
            };

            return authenticationInfo;
        }
    }
}
